<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
{
	style: {
		navigationStyle: 'custom',
		navigationBarTitleText: '首页',
	},
}
</route>
<template>
	<view class="bg-white h-full overflow-hidden">
		<!-- git commit --no-verify -m 'xxx' -->
		<fly-navbar fixed :backgroundColor="isTouch ? '#fff' : 'transparent'">
			<template v-slot:left>
				<view
					class="flex relative items-center justify-end pr-[20rpx] box-border h-[55rpx] rounded-[28rpx]"
					v-if="userInfo.student_id"
					:style="{ background: '#f1f1f1', paddingLeft: navHeight + 10 + 'rpx' }"
					@tap="toLink('/pages-user/account/index?type=back')"
				>
					<image
						class="absolute top-[50%] -translate-y-[50%] left-0 rounded-[50%]"
						:src="userInfo.avatar || baseImg + '/user-default.png'"
						:style="{ width: navHeight + 'rpx', height: navHeight + 'rpx' }"
					>
					</image>
                  
					<text class="text-[#181818] inline-block max-w-[220rpx] text-[26rpx] truncate">{{
						userInfo.username
					}}</text>
					<image class="w-[25rpx] h-[25rpx] ml-2" :src="baseImg + '/home/check-user.png'"></image>
				</view>
			</template>
		</fly-navbar>
		<view :class="['w-full', bannerList.length ? 'absolute top-0 left-0' : '']" style="padding-bottom: 200rpx;">
			<swiper
				v-if="bannerList.length"
				class="w-full h-[520rpx] student-swiper"
				:indicator-dots="bannerList.length > 1 ? true : false"
				indicator-active-color="#fff"
				indicator-color="rgba(255, 255, 255, .35)"
				autoplay
				circular
				:interval="3500"
				:duration="500"
			>
				<swiper-item v-for="item in bannerList" :key="item.cover_image" @tap="toPlan(item.url)">
					<image class="w-full h-full" :src="item.cover_image"> </image>
				</swiper-item>
			</swiper>

			<view class="px-4 pb-4 box-border">
				<view class="mt-4">
					<view class="w-full grid grid-cols-4">
						<view
							class="flex justify-center flex-col items-center"
							@tap="toLink('/pages-book/index')"
						>
							<image class="w-[88rpx] h-[88rpx]" :src="baseImg + '/home/ic-jianshu.png'"></image>
							<text class="text-center text-[#303030] text-[26rpx] mt-1">专家荐书</text>
						</view>
						<view
							class="flex justify-center flex-col items-center"
							@tap="toLink('/pages-plan/index')"
						>
							<image class="w-[88rpx] h-[88rpx]" :src="baseImg + '/home/ic-jihua.png'"></image>
							<text class="text-center text-[#303030] text-[26rpx] mt-1">共读计划</text>
						</view>
						<view class="flex justify-center flex-col items-center" @tap="proGramLink()">
							<image class="w-[88rpx] h-[88rpx]" :src="baseImg + '/home/ic-huodong.png'"></image>
							<text class="text-center text-[#303030] text-[26rpx] mt-1">展演活动</text>
						</view>
						<view
							class="flex justify-center flex-col items-center"
							@tap="toLink('/pages/shareBookstore/index')"
						>
							<image class="w-[88rpx] h-[88rpx]" :src="baseImg + '/home/ic-shuba.png'"></image>
							<text class="text-center text-[#303030] text-[26rpx] mt-1">共享书屋</text>
						</view>
					</view>
				</view>

				<view class="mt-4" v-if="userInfo.student_id && planList.length">
					<view class="w-full">
						<view class="text-[#303030] text-[33rpx] font-bold px-3 mb-3"
							>倍阅读共读计划 · {{ userInfo.grade_name }}</view
						>
						<view class="grid grid-cols-2 gap-x-[22rpx]">
							<view
								class="flex-1 h-[188rpx] relative"
								v-for="item in planList"
								:key="item.id"
								@tap="toLink('/pages-plan/details/index?id=' + item.id)"
							>
								<image
									class="w-full h-full absolute top-0 left-0 z-0 rounded-[25rpx]"
									:src="item.cover_img"
									mode="aspectFit"
								></image>
								<!-- <view
								class="w-full h-full flex flex-col justify-center absolute top-0 rounded-[25rpx] left-0 z-1 pl-6 box-border"
							>
								<text class="text-[#FFFFFF] text-[26rpx]">{{ item.title }}</text>
								<text class="text-[#FFFFFF] text-[21rpx] mt-3" v-if="item.status === 1"
									>共读进行中</text
								>
								<text class="text-[#FFFFFF] text-[21rpx] mt-3" v-if="item.status === 0"
									>下学期即将开始</text
								>
							</view> -->
							</view>
						</view>
					</view>
				</view>
                 
				<view class="mt-4" v-if="userInfo.student_id && learnList.length">
					<view class="w-full">
						<view class="text-[#303030] text-[33rpx] font-bold px-3 mb-3">上次学到</view>
						<swiper
							class="w-full h-[256rpx] student-swiper"
							:indicator-dots="learnList.length > 1 ? true : false"
							indicator-active-color="#fff"
							indicator-color="rgba(255, 255, 255, .35)"
							autoplay
							circular
							:interval="3500"
							:duration="500"
						>
							<swiper-item
								v-for="item in learnList"
								:key="item.book_id"
								@tap="
									toLink(
										'/pages-book/details/index?id=' + item.book_id + '&plan_id=' + item.plan_id,
									)
								"
							>
								<view
									class="w-full h-[256rpx] relative rounded-[30rpx]"
									style="background: linear-gradient(0deg, #ffd74f, #fbce35)"
								>
									<!-- <image
										class="w-full h-full absolute top-0 left-0 z-0 rounded-[30rpx]"
										:src="item.book_cover_img"
									></image> -->
									<view
										class="w-full h-full flex rounded-[30rpx] justify-between items-center px-[48rpx] py-[48rpx] box-border absolute top-0 left-0 z-1"
									>
										<view class="py-[12rpx] box-border" style="width: calc(100% - 180rpx)">
											<view class="text-[#fff] text-[33rpx] font-bold w-full line-clamp">{{
												item.book_name
											}}</view>
											<view class="text-[#fff] text-[24rpx] mt-1 line-clamp">{{
												item.paper_name
											}}</view>
											<view
												v-if="item.progress < 100"
												class="bg-[#F6815B] w-[166rpx] h-[50rpx] rounded-[25rpx] flex justify-center items-center text-[#fff] text-[24rpx] mt-3"
												>继续学习</view
											>
											<view
												v-if="item.book_integral === 0 && item.progress === 100"
												@tap.stop="receive(item)"
												class="bg-[#F6815B] w-[166rpx] h-[50rpx] rounded-[25rpx] flex justify-center items-center text-[#fff] text-[24rpx] mt-3"
												>领取积分</view
											>
											<view
												v-if="item.book_integral && item.progress === 100"
												class="bg-[#c6c6c6] w-[166rpx] h-[50rpx] rounded-[25rpx] flex justify-center items-center text-[#fff] text-[24rpx] mt-3"
												>已完成</view
											>
										</view>
										<view class="w-[180rpx] h-[180rpx] relative">
											<u-circle-progress
												inactive-color="rgba(0, 0, 0, .2)"
												bg-color="transparent"
												:active-color="'#ffffff'"
												:percent="item.progress"
												:border-width="10"
												:width="180"
											>
												<text class="text-[31rpx] text-[#fff]">{{ item.progress }}%</text>
											</u-circle-progress>
											<view
												v-if="item.single_book_integral"
												class="w-[94rpx] h-[42rpx] flex justify-center items-center absolute bottom-0 left-[50%] -translate-x-[50%] text-[21rpx] text-[#D9B22B] bg-white rounded-[21rpx]"
												style="box-shadow: 0rpx 3rpx 3rpx 0rpx rgb(48 101 206 / 30%)"
											>
												+{{ item.single_book_integral }}
											</view>
										</view>
									</view>
								</view>
							</swiper-item>
						</swiper>
					</view>
				</view>

				<view class="mt-4" v-if="rankingList.length">
					<view class="w-full">
						<view class="text-[#303030] text-[33rpx] font-bold px-3 mb-3">阅读达人</view>
						<view class="grid grid-cols-4 gap-x-2">
							<view
								class="flex flex-col justify-center items-center bg-white rounded-[30rpx] ranking-item px-2 pt-4 pb-2"
								v-for="(item, index) in rankingList.slice(0, 4)"
								:key="item.id"
							>
								<view class="w-[104rpx] h-[104rpx] relative">
									<image
										class="w-full h-full rounded-[50%] border-1 border-solid"
										:style="{ borderColor: rankingItemStyle[index].borderColor }"
										:src="item.avatar"
									></image>
									<image
										class="w-full h-[25rpx] absolute -bottom-[12rpx] left-0 z-1"
										:src="rankingItemStyle[index].img"
									></image>
									<view
										class="w-full h-[25rpx] absolute -bottom-[10rpx] flex justify-center items-center left-0 text-[#fff] text-[14rpx] z-2"
										>{{ item.integral }}分</view
									>
								</view>
								<text class="text-[#303030] text-[25rpx] mt-2 line-clamp-1">{{
									item.username
								}}</text>
							</view>
						</view>
					</view>
				</view>

				<view
					class="mt-4"
					v-for="item in bookList"
					:key="item.id"
					v-show="bookList.length && item.book_list.length"
				>
					<view class="w-full flex justify-between items-center mb-3">
						<view class="text-[#303030] text-[33rpx] font-bold px-3">{{ item.name }}</view>
						<view
							class="inline-block text-[#919191] text-[22rpx]"
							@tap="toLink('/pages-book/index?classify_id=' + item.id)"
						>
							更多
							<uni-icons type="forward" color="#919191" size="12"></uni-icons>
						</view>
					</view>
					<view class="w-full grid grid-cols-3 gap-x-4">
						<view
							class="w-[212rpx] flex flex-col items-center"
							v-for="cited in item.book_list"
							:key="cited.id"
							@tap="toBook(cited.id)"
						>
							<image class="w-full h-[250rpx] rounded-[40rpx]" :src="cited.cover_img"></image>
							<text
								class="text-[#303030] inline-block max-w-full text-[25rpx] mt-1 font-bold truncate"
								>{{ cited.name }}</text
							>
						</view>
					</view>
				</view>
			</view>
		</view>
	    <tab-bar></tab-bar>
	</view>
</template>

<script lang="ts" setup>
import { storeToRefs } from 'pinia';
import { useUserStore } from '@/store';
import useChangeTabbar from '@/hooks/useChangeTabbar';
import { toAuthPage } from '@/utils/jump';
import { getRankingPerson } from '@/service/ranking';
import { systemInfo } from '@/utils/getSystemInfo';
import { getDefaultUserInfo, getReceivePoint } from '@/service/user';
import { getHomeBannerList, getHomeBookList, getHomePlanList, getHomeLearn } from '@/service/home';
import { initializeApp } from '@/utils';
import onShare from '@/hooks/useShare';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
// const { onShareAppMessage, onShareTimeline } = onShare();
const { onShareAppMessage, onShareTimeline } = onShare();

useChangeTabbar(1);

const baseImg = ref(import.meta.env.VITE_STATIC_IMAGE);
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const { navHeight, statusBarHeight } = systemInfo();
const isTouch = ref(false);
const rankingItemStyle = [
	{
		borderColor: '#F7CF32',
		img: `${baseImg.value}/home/ranking-1.png`,
	},
	{
		borderColor: '#F88A76',
		img: `${baseImg.value}/home/ranking-2.png`,
	},
	{
		borderColor: '#6ED278',
		img: `${baseImg.value}/home/ranking-3.png`,
	},
	{
		borderColor: '#CFB75B',
		img: `${baseImg.value}/home/ranking-4.png`,
	},
];

const bannerList = ref([]);
const bookList = ref([]);
const planList = ref([]);
const rankingList = ref([]);
const learnList = ref([]);

onShow(() => {
	initializeApp(
		getBookList(),
		getBanner(),
		getPlanList(),
		getRanking(),
		userInfo.value.student_id && getLearBook(),
	);
	if (userInfo.value.student_id) getUserInfo();
});

onPageScroll(e => {
	const { scrollTop } = e;

	if (scrollTop * 2 < 520 - navHeight - statusBarHeight) {
		isTouch.value = false;
	} else {
		isTouch.value = true;
	}
});

const getUserInfo = async () => {
	const defaultUser = await getDefaultUserInfo();
	if (defaultUser.status_code === 200) {
		userStore.setUserInfo(defaultUser.data);
	}
};

const getBanner = async () => {
	const res = await getHomeBannerList();
	if (res.status_code === 200 && res.data) {
		bannerList.value = res.data;
	}
};

const goTalk = () => {
	//console.log(123)
	uni.navigateTo({
		url:'/pages/talk/index'
	})
}

const getLearBook = async () => {
	const res = await getHomeLearn({ student_id: userInfo.value.student_id });
	if (res.status_code === 200 && res.data) {
		learnList.value = res.data;
	}
};

const getPlanList = async () => {
	const res = await getHomePlanList();
	if (res.status_code === 200 && res.data) {
		planList.value = res.data;
	}
};

const getRanking = async () => {
	const res = await getRankingPerson(1);
	if (res.status_code === 200 && res.data) {
		rankingList.value = res.data.list || [];
	}
};

const getBookList = async () => {
	const res = await getHomeBookList();
	if (res.status_code === 200 && res.data) {
		bookList.value = res.data;
	}
};

const toBook = (id: number) => {
	if (id === undefined) return;
	if (!userInfo.value.student_id) {
		uni.navigateTo({
			url: `/pages-book/details/index?id=${id}`,
		});
		// toAuthPage({}, { type: 'navigateTo', url: `/pages-book/details/index?id=${id}` });
	} else {
		uni.navigateTo({
			url: `/pages-book/details/index?id=${id}`,
		});
	}
};

const toLink = (url: string) => {
	if (!url) return;
	if (!userInfo.value.student_id && url.includes('pages/shareBookstore/index')) {
		toAuthPage();
		return;
	}
	uni.navigateTo({
		url,
	});
	
};

const toPlan = (url: string) => {
	 // console.log(url);
	 // if(url == 'https://activity.etjbooks.com.cn/') {
		//  console.log(url);
		//  var obj =  {
		// 	 url:'https://account.etjbooks.com.cn/login',
		// 	 title:'h5页面'
		//  }
		//  uni.setStorageSync('webInfo',obj);
		//  uni.navigateTo({
		//  	url:'pages/web-view/index'
		//  })
	 // }
	if (!url) {
		toLink('/pages-plan/index');
		return;
	}
	if (!userInfo.value.student_id) {
		toAuthPage();
		return;
	}
	uni.navigateTo({
		url,
	});
};

const proGramLink = () => {
	uni.navigateToMiniProgram({
		appId: 'wx62add167a6ada00d',
		path: 'pagesC/index',
		success() {
			// 打开成功
		},
	});
};

const receive = async item => {
	uni.showLoading({
		title: '领取中...',
	});
	try {
		const res = await getReceivePoint({
			student_id: userInfo.value.student_id,
			book_id: item.book_id,
			plan_id: item.plan_id,
		});
		uni.hideLoading();
		if (res.status_code === 200) {
			uni.showToast({
				icon: 'none',
				title: '领取成功',
				success: () => {
					getLearBook();
				},
			});
		} else {
			uni.showToast({
				icon: 'none',
				title: res.message,
			});
		}
	} catch (error) {
		uni.hideLoading();
		uni.showToast({
			icon: 'none',
			title: '领取失败,请重试',
		});
	}
};

watch(
	userInfo,
	newVal => {
		if (newVal.student_id) {
			getLearBook();
		}
	},
	{ immediate: true },
);
</script>

<style lang="scss">
page {
	&::after {
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 9999;
		width: 100%;
		height: 1rpx;
		content: '';
		background: transparent;
		box-shadow: 0rpx -2rpx 20rpx 2rpx rgb(165 165 165 / 34%);
	}
}

.student-swiper {
	/* #ifdef APP-PLUS  || H5 */
	.uni-swiper .uni-swiper-dot {
		width: 10rpx;
		height: 10rpx;
	}
	/* #endif */
	/* #ifdef MP-WEIXIN */
	.wx-swiper-dots .wx-swiper-dot {
		width: 10rpx;
		height: 10rpx;
	}
	/* #endif */
}
</style>
<style lang="scss" scoped>
page {
	&::after {
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 9999;
		width: 100%;
		height: 1rpx;
		content: '';
		background: transparent;
		box-shadow: 0rpx -2rpx 20rpx 2rpx rgb(165 165 165 / 34%);
	}
}

:deep(.uni-swiper__dots-item) {
	height: 4rpx !important;
}

.ranking-item {
	box-shadow:
		0rpx 0rpx 3rpx 0rpx rgb(0 0 0 / 3%),
		0rpx 5rpx 21rpx 0rpx rgb(0 0 0 / 7%);
}

</style>
